/****************************************************************************
**
** Copyright (C) 2012 Róbert Márki
**
** This file is part of Web Feeds.
**
** Web Feeds is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** Web Feeds is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Web Feeds.  If not, see <http://www.gnu.org/licenses/>.
****************************************************************************/

import QtQuick 1.1
import com.nokia.meego 1.0
import com.nokia.extras 1.1
import WebFeeds 1.0
import GoogleReader 1.0
import "../../../../shared/qml" as Shared
import "../../../../shared/qml/UIConstants.js" as UIConstants
import "../delegates" as Delegates

Shared.CommonSheet {
    id: root

    property variant service
    acceptButtonText: qsTr("Subscribe")
    rejectButtonText: qsTr("Cancel")
    title: qsTr("Subscribe to feed")
    busyText: qsTr("Subscribing")

    Connections {
        target: root.service
        onFeedAddingFinished: root.onFeedAddingFinished(result)
    }

    function onFeedAddingFinished(result) {
        if((result == GoogleReaderEnum.ErrNoError)
           || (result == GoogleReaderEnum.ErrAborted)) {
            root.close();
            return;
        }
        root.busy = false;
        if(result == GoogleReaderEnum.ErrNetworkError)
            root.showMessage(qsTr("Network error"));
        else
            root.showMessage(qsTr("Failed to subscribe to feed"));
    }
    onAccepted: {
        root.busy = true;
        root.open();
        root.service.addFeed(addressField.text);
    }
    onRejected: {
        if(root.busy) {
            root.open();
            root.service.abortAddFeed(root.pageItem);
        }
    }

    contentItem: Column {
        anchors.fill: parent
        spacing: 0

        Column {
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.leftMargin: UIConstants.DEFAULT_MARGIN
            anchors.rightMargin: UIConstants.DEFAULT_MARGIN
            spacing: UIConstants.DEFAULT_HALF_MARGIN
            Label {
                text: qsTr("Address")
                font.family: UIConstants.FONT_FAMILY_LIGHT
            }
            Shared.TextField {
                id: addressField
                width: parent.width
                property bool suggestionsDisabled: false
                placeholderText: qsTr("Enter the address or search terms")
                onTextChanged: {
                    root.acceptButton.enabled = addressField.text.length;
                    if((addressField.text.length > 0) && !addressField.suggestionsDisabled)
                        searchTimer.restart();
                }
                platformSipAttributes: SipAttributes {
                    actionKeyEnabled: root.acceptButton.enabled
                    actionKeyLabel: root.acceptButtonText
                    actionKeyHighlighted: true
                }
                Keys.onReturnPressed: {
                    if(root.acceptButton.enabled)
                        root.accept();
                }
                Timer {
                    id: searchTimer
                    interval: 1000;
                    onTriggered: {
                        suggestionsBusyIndicator.visible = true;
                        var searchTerms = addressField.text;
                        searchTerms.trim();
                        root.service.findFeeds(searchTerms);
                    }
                }
                Connections {
                    target: root.service
                    onFeedSearchFinished: {
                        suggestionsBusyIndicator.visible = false;
                        if(result == GoogleReaderEnum.ErrNoError) {
                            suggestionsModel.clear();
                            for(var i = 0; i < titles.length; ++i)
                                suggestionsModel.append({"title": titles[i], "url": urls[i]});
                        } else if(result == GoogleReaderEnum.ErrNetworkError) {
                            root.showMessage(qsTr("Network error"));
                        } else {
                            root.showMessage(qsTr("Failed to retrieve the suggestions"));
                        }
                    }
                }
            }
            Shared.LabeledSeparator {
                text: qsTr("Suggestions")
            }
        }
        ListView {
            id: suggestionsListView
            height: root.height - mapToItem(root, 0, 0).y
            width: parent.width
            clip: true
            cacheBuffer: 100 * UIConstants.DEFAULT_DELEGATE_HEIGHT
            model: ListModel {id: suggestionsModel}            
            delegate: Delegates.AddFeedSheetDelegate {
                id: suggestionsDelegate
                titleColor: (addressField.text == model.subtitle) ? UIConstants.HIGHLIGHT_COLOR : "black"
                onReleased: {
                    addressField.suggestionsDisabled = true;
                    addressField.text = model.url
                    addressField.selectAll();
                    addressField.suggestionsDisabled = false;
                }
            }
            BusyIndicator {
                id: suggestionsBusyIndicator
                anchors.centerIn: parent
                style: BusyIndicatorStyle { size: "large"}
                visible: false
                running: true
            }            
        }
        ScrollDecorator {
            flickableItem: suggestionsListView
        }
        Connections {
            target: root
            onStatusChanged: {
                if(root.status == DialogStatus.Open) {
                    addressField.forceActiveFocus();
                    addressField.platformOpenSoftwareInputPanel();
                }
            }
        }
    }
}
